package com.suzhe.ymall.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.suzhe.ymall.promotion.api.UserApi;
import com.suzhe.ymall.common.pojo.ApiResEntity;
import com.suzhe.ymall.common.pojo.AppLoginUser;
import com.suzhe.ymall.common.utils.*;
import com.suzhe.ymall.user.param.LoginParam;
import com.suzhe.ymall.user.param.RegisterParam;
import com.suzhe.ymall.user.pojo.User;
import com.suzhe.ymall.user.service.IUserService;
import com.suzhe.ymall.promotion.vo.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author suzhe
 * @since 2019-08-12
 */
@RestController
@RequestMapping("user")
@Slf4j
public class UserController implements UserApi {

    @Autowired
    RedisTemplateUtils redisTemplateUtils;
    @Autowired
    IUserService iUserService;

    /**
     * 登录
     */
    @PostMapping("/login")
    public ApiResEntity login(@RequestBody LoginParam loginParam) {
        log.info("login params:{}", loginParam);
        User user = iUserService.getOne(new QueryWrapper<User>().eq("phone_number", loginParam.getPhoneNumber()));
        String encryptPassword = PasswordUtils.getEncryptPassword(loginParam.getPassword(), user.getSalt());
        if (user != null && user.getPassword().equals(encryptPassword)) {
            AppLoginUser loginUser = new AppLoginUser();
            loginUser.setId(user.getId())//
                    .setUsername(user.getUsername())//
                    .setNickName(user.getNickname())//
                    .setPhoneNumber(user.getPhoneNumber());
            String token = YMStringUtils.getUUID();
            String tokenKey = RedisKeys.getTokenKeyForApp(token);
            redisTemplateUtils.set(tokenKey, loginUser, YMConstant.APP_TOKEN_EXPIRE_TIME);
            return ApiResEntity.ok(token);
        }
        return ApiResEntity.error("密码输入错误");
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public ApiResEntity register(@RequestBody RegisterParam registerParam) {
        log.info("registerParam:{}",registerParam);
        User eUser = iUserService.getOne(new QueryWrapper<User>().eq("phone_number", registerParam.getPhoneNumber()));
        if (eUser != null){
            return ApiResEntity.error("该手机号已注册");
        }
        User user = new User();
        user.setPhoneNumber(registerParam.getPhoneNumber());
        user.setUsername(registerParam.getPhoneNumber());
        String salt = YMStringUtils.createRandom(false, 6);
        user.setSalt(salt);
        String encryptPassword = PasswordUtils.getEncryptPassword(registerParam.getPassword(), user.getSalt());
        user.setPassword(encryptPassword);
        iUserService.save(user);
        return ApiResEntity.ok();
    }


    @PostMapping("/logout")
    public ApiResEntity logout(HttpServletRequest request) {
        String accessToken = request.getHeader(YMConstant.ACCESS_TOKEN);
        String tokenKey = RedisKeys.getTokenKeyForApp(accessToken);
        redisTemplateUtils.del(tokenKey);
        return ApiResEntity.ok();
    }

    @GetMapping("/verifyLogin")
    public ApiResEntity verifyLogin(HttpServletRequest request){
        AppLoginUser appLoginUser = LoginUserUtils.getAppLoginUser();
        if (appLoginUser != null){
            return ApiResEntity.ok();
        }
        return ApiResEntity.error();
    }


    @GetMapping("/queryUserVosByPhoneNumbers")
    @Override
    public List<UserVo> queryUserVosByPhoneNumbers(@RequestParam("phoneNumbers") List<String> phoneNumbers) {
        List<User> users = (List)iUserService.list(new QueryWrapper<User>().in("phone_number",phoneNumbers));
        List<UserVo> userVos = new ArrayList<>();
        for (User user: users){
            UserVo userVo = new UserVo();
            userVo.setId(user.getId());
            userVo.setNickname(user.getNickname());
            userVo.setLevel(user.getLevel());
            userVo.setPhoneNumber(user.getPhoneNumber());
            userVo.setUsername(user.getUsername());
            userVos.add(userVo);
        }
        return userVos;
    }
}
